package com.wuyanzu.shixicoderedo.service.impl;

import com.wuyanzu.shixicoderedo.service.TokenService;
import com.wuyanzu.shixicoderedo.common.utils.jwt.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class JwtTokenService implements TokenService {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public String getUserIdFromToken(String token) {
        if (token == null) return null;
        if (token.toLowerCase().startsWith("bearer ")) token = token.substring(7).trim();
        if (token.isBlank()) return null;
        try {
            Claims claims = jwtUtil.parseToken(token);
            if (claims.get("userId") != null) return String.valueOf(claims.get("userId"));
            if (claims.getSubject() != null) return claims.getSubject();
            return null;
        } catch (JwtException ex) {
            // 已在 jwtUtil 中记录更详细日志，这里可选记录
            return null;
        } catch (Exception e) {
            return null;
        }
    }
}
